package com.example.navigation.views

import android.content.Context
import android.graphics.Color.parseColor
import android.location.LocationManager
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.LifecycleEventObserver
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Poi
import com.amap.api.maps.model.PolylineOptions
import com.amap.api.navi.AmapNaviPage
import com.amap.api.navi.AmapNaviParams
import com.amap.api.navi.AmapNaviType
import com.amap.api.navi.AmapPageType
import com.example.navigation.R
import com.example.navigation.api.navigation.Line
import com.example.navigation.api.navigation.LineColor
import com.example.navigation.api.navigation.LineSegment
import com.example.navigation.api.navigation.Lines
import com.example.navigation.api.navigation.NavigationApi
import com.example.navigation.api.navigation.PointIndex
import com.example.navigation.components.DropDownAreas
import com.example.navigation.components.DropDownDevices
import com.example.navigation.components.MyDateRangePicker
import com.example.navigation.components.RoadRankDialog
import com.example.navigation.viewModel.MapViewModel
import com.example.navigation.viewModel.StatisticsViewModel
import java.util.Timer
import java.util.TimerTask


/**
 * Created with IntelliJ IDEA.
 * @Author: Liao Run
 * @Date: 2024-06-08 15:48
 * @Description:
 **/

var mediaPlayer: MediaPlayer? = null
const val pointInterval = 6
val needNavigationRouter: LineSegment = arrayListOf()

@Composable
fun MapPage(
    context: Context,
    savedInstanceState: Bundle?,
    mapViewModel: MapViewModel,
    statisticsViewModel: StatisticsViewModel = hiltViewModel(),
) {

    var isUserClicked by remember {
        mutableStateOf(false)
    }

    var timer by remember {
        mutableStateOf(Timer())
    }
    // 地图组件对象
    var mapView by remember {
        mutableStateOf<MapView?>(null)
    }


    LaunchedEffect(key1 = Unit) {
        // 获取音频文件信息
        val prompt = context.resources.openRawResourceFd(R.raw.prompt)
        // 创建音频播放器
        mediaPlayer = MediaPlayer()
        mediaPlayer!!.setDataSource(
            prompt.fileDescriptor,
            prompt.startOffset, prompt.length
        )
        mediaPlayer!!.setOnPreparedListener {
            Log.i(this.toString(), "MapPage: 媒体播放准备好了")
        }
        // 准备播放
        mediaPlayer?.prepareAsync()

        mapViewModel.searchRes.collect {
            if (it.code == 1) {
                // 清除地图
                mapView?.map?.clear()
                needNavigationRouter.clear()
                // 绘制所有的线
                drawLines(it.data, isUserClicked, mapView, context)
                // 后面是定时刷新，不是用户点击的
                isUserClicked = false
            }
        }
    }


    // 获取当前的什么周期
    val lifecycleOwner = LocalLifecycleOwner.current

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            Log.w(this.toString(), "MapPage: $event")
            when (event) {
                androidx.lifecycle.Lifecycle.Event.ON_CREATE -> {}
                androidx.lifecycle.Lifecycle.Event.ON_START -> {}
                androidx.lifecycle.Lifecycle.Event.ON_RESUME -> mapView?.onResume()
                androidx.lifecycle.Lifecycle.Event.ON_PAUSE -> mapView?.onPause()
                androidx.lifecycle.Lifecycle.Event.ON_STOP -> {
                }

                androidx.lifecycle.Lifecycle.Event.ON_DESTROY -> mapView?.onDestroy()
                androidx.lifecycle.Lifecycle.Event.ON_ANY -> {}
            }
        }

        // 添加声明周期监听，来处理地图的生命周期
        lifecycleOwner.lifecycle.addObserver(observer)

        onDispose {
            // 移除监听
            lifecycleOwner.lifecycle.removeObserver(observer)
            timer.cancel()
            mapView?.onDestroy()
        }
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.LightGray)
    ) {

        var deviceId by remember {
            mutableStateOf("")
        }
        var startTime by remember {
            mutableStateOf("")
        }
        var endTime by remember {
            mutableStateOf("")
        }

        var areaName by remember {
            mutableStateOf("")
        }
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceAround
        ) {
            DropDownDevices(
                modifier = Modifier
            ) {
                // 选择了时间的同时发送请求
                Log.i(this.toString(), "MapPage: $it")
                deviceId = it
                if (startTime.isNotEmpty() && endTime.isNotEmpty()) {
                    // 已经选择了时间段，可以发送请求
                    isUserClicked = true

                    // 定时刷新
                    timer.cancel()
                    // 必须重新创建一个Timer
                    timer = Timer()
                    timer.schedule(object : TimerTask() {
                        override fun run() {
                            mapViewModel.searchNavigationData(
                                NavigationApi.SearchNavigationDataParams(
                                    beDate = startTime,
                                    endDate = endTime,
                                    deviceId = it,
                                    lx = 0
                                )
                            )

                            if (areaName.isNotEmpty()) {
                                statisticsViewModel.getRoadPmStatisticRank(
                                    startTime,
                                    endTime,
                                    qy = areaName
                                )
                            }
                        }
                    }, 0, 7000)
                }
            }

            DropDownAreas {
                areaName = it
                if (startTime.isNotEmpty() && endTime.isNotEmpty()) {
                    timer.cancel()
                    timer = Timer()
                    timer.schedule(object : TimerTask() {
                        override fun run() {
                            // 请求道路积尘排名数据
                            statisticsViewModel.getRoadPmStatisticRank(startTime, endTime, it)

                            if (deviceId.isNotEmpty()) {
                                // 请求道路积尘数据
                                mapViewModel.searchNavigationData(
                                    NavigationApi.SearchNavigationDataParams(
                                        beDate = startTime, endDate = endTime, deviceId = deviceId, lx = 0
                                    )
                                )
                            }
                        }
                    }, 0, 7000)
                }
            }
            Button(onClick = {
                val localeManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
                val gpsEnable = localeManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
                if (!gpsEnable) {
                    Toast.makeText(context, "打开定位服务才能导航!", Toast.LENGTH_SHORT).show()
                    return@Button
                }
                if (mapViewModel.searchRes.value.data != null) {
                    // 停止获取数据，防止刷新
                    timer.cancel()
                    // 每隔7个点取一个坐标
                    // 起点信息
                    val endIndex = 17 * pointInterval
                    val endPoint = needNavigationRouter[endIndex]
//                val start = NaviPoi("当前起点", LatLng(startPoint[1], startPoint[0]), null)

                    // 终点信息
                    val end = Poi(
                        "当前终点",
                        LatLng(
                            endPoint[PointIndex.latitude.ordinal].toDouble(),
                            endPoint[PointIndex.longitude.ordinal].toDouble()
                        ),
                        null
                    )

                    // 添加16途经点信息
                    val waysPoiIds: MutableList<Poi> = arrayListOf()
                    for (i in 1..16) {
                        val point = needNavigationRouter[i * pointInterval]
                        waysPoiIds.add(
                            Poi(
                                "途经点${i}",
                                LatLng(
                                    point[PointIndex.latitude.ordinal].toDouble(),
                                    point[PointIndex.longitude.ordinal].toDouble()
                                ),
                                null
                            )
                        )
                    }

                    // POI算路
                    // POI算路
                    // 组件参数配置
                    val params = AmapNaviParams(null, waysPoiIds, end, AmapNaviType.DRIVER, AmapPageType.NAVI)
                    // 启动组件
                    AmapNaviPage.getInstance()
                        .showRouteActivity(context, params, MyNavInfoCallback(needNavigationRouter, endIndex, context))

                } else {
                    Toast.makeText(context, "查询一条路线才能按路线导航", Toast.LENGTH_SHORT).show()
                }
            }) {
                Text(text = "导航", fontSize = 13.sp)
            }
        }

        MyDateRangePicker(context) { beDate, endDate ->
            startTime = beDate
            endTime = endDate
            if (deviceId.isNotEmpty()) {
                // 发送请求
                isUserClicked = true
                timer.cancel()
                timer = Timer()
                timer.schedule(object : TimerTask() {
                    override fun run() {
                        mapViewModel.searchNavigationData(
                            NavigationApi.SearchNavigationDataParams(
                                beDate, endDate, deviceId, 0
                            )
                        )

                        if (areaName.isNotEmpty()) {
                            statisticsViewModel.getRoadPmStatisticRank(
                                startTime,
                                endTime,
                                qy = areaName
                            )
                        }
                    }
                }, 0, 7000)

            }
        }


        AndroidView(factory = {
            if (mapView == null) {
                val mapView1 = MapView(context)
                mapView1.onCreate(savedInstanceState)
                // 不能旋转
                mapView1.map.uiSettings.isRotateGesturesEnabled = false
                // 不能倾斜
                mapView1.map.uiSettings.isTiltGesturesEnabled = false
                mapView1.map.uiSettings.isZoomControlsEnabled = false
                mapView1.map.moveCamera(CameraUpdateFactory.newLatLng(LatLng(30.657401, 104.065861)))
                mapView = mapView1
            }
            mapView!!
        }) {
        }
    }

    RoadRankDialog()
}

fun drawLines(lines: Lines?, isUserClicked: Boolean, mapView: MapView?, context: Context) {
    if (lines != null) {
        for (i in lines.indices) {
            drawLine(lines[i], i == lines.lastIndex, mapView, context, isUserClicked)
        }
    }
}

fun drawLine(
    map: Line,
    isLastLine: Boolean,
    mapView: MapView?,
    context: Context,
    isUserClicked: Boolean,
) {

    // 上一条线段的key,格式(size_color_size)
    var prevKey: LineColor? = null
    // 当前绘制的线段的point
    var lineSegment: LineSegment? = null
    var lineColor: LineColor = ""
    // 遍历一段段不同颜色的线段，拼成整条线
    for (currentKey in map.keys) {
        // 把下一条线的第一个点加到上一条线的尾巴上，这样才能让线连接起来

        prevKey?.let {
            val split = prevKey!!.split('_')
            lineColor = split[1]
            lineSegment = map[prevKey]
            lineSegment?.add(map[currentKey]!![0])
        }


        // 上一条线完整了，可以绘制 or 绘制最后一个线段
        when (lineColor) {
            "alarm" -> {
                lineColor = "#1c9300"
            }

            "normal" -> {
                lineColor = "#fff913"
            }

            "over" -> {
                lineColor = "#ff0000"
            }

            "hser" -> {
                lineColor = "#ffa70c"
            }

            else -> {
                lineColor = "#1c9300"
            }
        }
        val pointers = lineSegment?.map {
            LatLng(it[PointIndex.latitude.ordinal].toDouble(), it[PointIndex.longitude.ordinal].toDouble())
        }

        mapView!!.map.addPolyline(
            PolylineOptions().addAll(pointers)
                .color(parseColor(lineColor))
        )

        // 绘制最后一条线段
        if (currentKey == map.keys.last()) {
            val split = currentKey.split('_')
            lineColor = split[1]
            lineSegment = map[currentKey]
            // 上一条线完整了，可以绘制 or 绘制最后一个线段
            when (lineColor) {
                "alarm" -> {
                    lineColor = "#1c9300"
                }

                "normal" -> {
                    lineColor = "#fff913"
                }

                "over" -> {
                    lineColor = "#ff0000"
                }

                "hser" -> {
                    lineColor = "#ffa70c"
                }

                else -> {
                    lineColor = "#1c9300"
                }
            }
            val points = lineSegment?.map {
                LatLng(it[PointIndex.latitude.ordinal].toDouble(), it[PointIndex.longitude.ordinal].toDouble())
            }
            mapView.map.addPolyline(
                PolylineOptions().addAll(points)
                    .color(parseColor(lineColor))
            )
        }

        needNavigationRouter.addAll(lineSegment ?: emptyList())

        prevKey = currentKey
    }

    // 绘制完最后一条线 && 用户点击的第一次查询结果绘制
    if (isLastLine) {

        // 最后一段线段是红色
        if (lineColor == "#ff0000") {
            if (mediaPlayer?.isPlaying?.not() == true) {
                mediaPlayer!!.start()
            }
            Toast.makeText(context, "当前路段的积尘值超标!", Toast.LENGTH_SHORT).show()
        }

        if (isUserClicked) {
            // 移动镜头到最后一个点的位置
            if (lineSegment != null) {
                mapView?.map?.moveCamera(
                    CameraUpdateFactory.newLatLng(
                        LatLng(
                            lineSegment!!.last()[PointIndex.latitude.ordinal].toDouble(),
                            lineSegment!!.last()[PointIndex.longitude.ordinal].toDouble()
                        )
                    )
                )
            } else {
                Toast.makeText(context, "没有数据", Toast.LENGTH_SHORT).show()
            }
        }

    }
}
